package com.xylx.interview.loadbalance;

import java.util.HashMap;
import java.util.Map;

/**
 * 平滑加权轮询算法
 */
public class SmoothWeightPollServer {

    public static Map<String, SmoothWeight> map = new HashMap<>();

    static {
        map.put("10.180.11.126:8888", new SmoothWeight(5, 5, "10.180.11.126:8888"));
        map.put("10.180.11.128:8888", new SmoothWeight(2, 2, "10.180.11.128:8888"));
        map.put("10.180.11.130:8888", new SmoothWeight(4, 4, "10.180.11.130:8888"));
    }

    public static String getServer() {
        SmoothWeight maxSmoothWeight = null;
        int weight = map.values().stream().mapToInt(SmoothWeight::getWeight).sum();

        for (Map.Entry<String, SmoothWeight> entry : map.entrySet()) {
            SmoothWeight currentSmoothWeight = entry.getValue();
            if (maxSmoothWeight == null || currentSmoothWeight.getCurrentWeight() > maxSmoothWeight.getCurrentWeight()) {
                maxSmoothWeight = currentSmoothWeight;
            }
        }
        assert maxSmoothWeight != null;
        maxSmoothWeight.setCurrentWeight(maxSmoothWeight.getCurrentWeight() - weight);
        for (Map.Entry<String, SmoothWeight> entry : map.entrySet()) {
            SmoothWeight currentSmoothWeight = entry.getValue();
            currentSmoothWeight.setCurrentWeight(currentSmoothWeight.getCurrentWeight() + currentSmoothWeight.getWeight());
        }

        return maxSmoothWeight.getAddress();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 15; i++) {
            System.out.println(getServer());
        }
    }
}